package com.qf.service.impl;

import com.qf.service.OrderService;
import com.qf.dao.CartDao;
import com.qf.dao.OrderDao;
import com.qf.dao.OrderDetailDao;
import com.qf.pojo.Cart;
import com.qf.pojo.Order;
import com.qf.pojo.OrderDetail;
import com.qf.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderDao orderDao;
    @Autowired
    CartDao cartDao;
    @Autowired
    OrderDetailDao orderDetailDao;

    @Override
    public Order addOrder(int aid, int uid) {
        //获取当前用户购物车信息
        List<Cart> carts = cartDao.getCarts(uid);
        double sum = 0;

        for (Cart cart:carts) {
            //计算订单总额
            sum += cart.getMoney();
        }

        //添加订单
        Order order = new Order();
        //生成唯一订单编号
        String orderId = RandomUtils.createActive();

        order.setId(orderId);
        order.setUid(uid);
        order.setAid(aid);
        order.setMoney(sum);
        order.setStatus("1");
        order.setTime(new Date());

        //更新购物车
        orderDao.insert(order);

        //添加订单详情
        for (Cart cart:carts) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOid(orderId);
            orderDetail.setPid(cart.getpId());
            orderDetail.setNum(cart.getNum());
            orderDetail.setMoney(sum);

            //更新购物车
            orderDetailDao.insert(orderDetail);
        }
        return order;
    }

    @Override
    public List<Order> getOrderList(int id) {
        return orderDao.getOrderList(id);
    }

    @Override
    public void updateOrderStatus(String orderId, String status) {
        orderDao.updateOrderStatus(orderId,status);
    }

    @Override
    public List<Order> searchOrder() {
        return orderDao.searchOrder();
    }

    @Override
    public OrderDetail getOrderDetail(String id) {
        return orderDao.getOrderDetail(id);
    }

    @Override
    public void orderStatus(String oid) {
        orderDao.orderStatus(oid);
    }

    @Override
    public List<Order> findOrderDetail(int id, String status) {
        return orderDao.findOrderDetail(id,status);
    }
}
